package com.rsstuan.web.cron.controller;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;

import com.rsstuan.data.TuanGouWebItem;
import com.rsstuan.service.ChannelService;
import com.rsstuan.storage.data.TuanGouChannelData;
import com.rsstuan.storage.data.TuanGouItemData;
import com.rsstuan.storage.impl.JDOTuanGouItemStorage;
import com.rsstuan.utils.CharSetUtils;
import com.rsstuan.utils.CityUtils;
import com.rsstuan.utils.ItemUtils;
import com.rsstuan.utils.StringUtils;
import com.rsstuan.web.controller.SpringController;

public class PublishController extends SpringController {
    
	private static final Logger LOG = Logger.getLogger(PublishController.class.getName());
	
	private String subUrl = "http://www.jiechaer.com/php/receive.php";
	
	private VelocityConfigurer velocityConfig;
	    
	private Properties props;
	    
	private Session session;
	
	public PublishController() {
		props = new Properties();
		session = Session.getDefaultInstance(props, null);
	}
	public void setSubUrl(String subUrl) {
		this.subUrl = subUrl;
	}
	
	public void setVelocityConfig(VelocityConfigurer velocityConfig) {
	        this.velocityConfig = velocityConfig;
	 }



	public ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String template = "main/pub.vm";
		URL url = new URL(subUrl + "?file=index.htm");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestMethod("POST");
		OutputStreamWriter output = new OutputStreamWriter(connection
				.getOutputStream(), "UTF-8");
		BufferedWriter writer = new BufferedWriter(output);
		StringWriter sw = new StringWriter();
		Map<String, Object> context = getWebMap();
		
		VelocityEngineUtils.mergeTemplate(velocityConfig.getVelocityEngine(),
				template, context, sw);
		writer.write(sw.toString());
		writer.flush();
		
		connection.getInputStream();
		LOG.info("send post to " + url.toString());
		
		renderText(response, sw.toString());
		
		return null;

	}
	
	private Map<String, Object> getWebMap() {
		 JDOTuanGouItemStorage itemStorage = new JDOTuanGouItemStorage();
	        String city = null;
	        int cityid = 1;
	        
	        if (city == null)
	        	city = CityUtils.DEFAULT_CITY;
	        Map<Long, TuanGouChannelData> channelMap = ChannelService.getInstance().getAllChannelsMap();
	        TuanGouItemData[] items = itemStorage.getActiveItemsByCity(city);
			List<TuanGouWebItem> webItems = new ArrayList<TuanGouWebItem>();
			for (TuanGouItemData item : items) {
	        	if (ItemUtils.validate(item)) {
		            TuanGouWebItem witem = new TuanGouWebItem(item);
		            TuanGouChannelData channel = channelMap.get(item.getChannelId());
		            if (channel != null)
		            	witem.setSiteName(channel.getTitle() + "(" + channel.getCity() + ")");
		            webItems.add(witem);
	        	}
	        }
			TuanGouWebItem[] witemArray = webItems.toArray(new TuanGouWebItem[0]);
			
			String priceseq = ItemUtils.sortByPrice(witemArray);
			String discountseq = ItemUtils.sortByDiscount(witemArray);
			String buyseq = ItemUtils.sortByOrderNumDesc(witemArray);
			

	        Map<String, Object> map = new HashMap<String, Object>();
	        map.put("StringUtils", StringUtils.getInstance());
	        map.put("peoplesequence", buyseq);
	        map.put("pricesequence", priceseq);
	        map.put("discountsequence", discountseq);
	        map.put("items", witemArray);
	        map.put("cityid", cityid);
	        map.put("city", city);
	        
	        return map;
	
	}

}
